package org.elanfox.intellicommunity.common.resource.impl;

import com.aliyun.oss.OSSClient;
import org.elanfox.intellicommunity.common.constant.Constant;
import org.elanfox.intellicommunity.common.resource.StaticResourceService;
import org.elanfox.intellicommunity.common.resource.base.OSSFileResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author allan
 * @date 2018-02-24
 */
@Service("resourceService")
@Profile(value = {Constant.PROFILE_CONTAINER})
public class OSSResourceServiceImpl implements StaticResourceService {
    @Autowired
    public Environment environment;
    private final String bucketName;

    private final String resourceDomain;

    private OSSClient ossClient;

    @Autowired
    public OSSResourceServiceImpl(Environment environment) {
        String endpoint = environment.getProperty(Constant.OSS_END_POINT, "oss-cn-shenzhen.aliyuncs.com");
        String accessKeyId = environment.getProperty(Constant.OSS_ACCESS_KEY_ID, "LTAI4FgniksE2mBLEU97WxeV");
        String accessKeySecret = environment.getProperty(Constant.OSS_ACCESS_KEY_SECRET, "HlHIbd06hMjnbzA2dwGy4CAXO6nUyN");
        bucketName = environment.getProperty(Constant.OSS_BUCKET_NAME, "spot-mall-dev");
        this.resourceDomain = environment.getProperty(Constant.OSS_RESOURCE_DOMAIN, "http://spot-mall-dev.oss-cn-shenzhen.aliyuncs.com/");

        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    @Override
    public Resource upload(String path, InputStream data) throws URISyntaxException {
        ossClient.putObject(bucketName, path, data);
        return get(path);
    }

    @Override
    public Resource get(String path) throws URISyntaxException {
        String url = resourceDomain + path;

        return new OSSFileResource(new URI(url));
    }

    @Override
    public void delete(String path) {
        ossClient.deleteObject(bucketName, path);
    }
}
